 package com.myownthemepark.s3vn;

import com.myownthemepark.s3vn.S3vn;

import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

public class StartCommitHook {
	public static void main(String[] args){
		String svnZooBucket = null;
		String svnZooPrefix = null;
		String svnZooZKAddr = null;
		String svnZooZKPrefix = null;
		String repoPath = null;
		String user = null;
		String capabilities = null;
		S3vn s3vn = null;
		long currentLocal, rev;
		int currentZoo, ret;
		boolean failure = false;
		Logger logger = Logger.getLogger(StartCommitHook.class);
		BasicConfigurator.configure();
		
		if (args.length < 3){
			System.out.println("Usage: java StartCommitHook <repos_path> <user> <capabilities>");
			return;
		}
		
		try{
			repoPath = args[0];
			user = args[1];
			capabilities = args[2];
			
			svnZooBucket = System.getenv("SVNZOO_BUCKET");
			svnZooPrefix = System.getenv("SVNZOO_PREFIX");
			svnZooZKAddr = System.getenv("SVNZOO_ZKADDR");
			svnZooZKPrefix = System.getenv("SVNZOO_ZKPREFIX");
			s3vn = new S3vn(repoPath, svnZooBucket, svnZooPrefix, svnZooZKAddr, svnZooZKPrefix);
			s3vn.setProgName("start");
			
			s3vn.createZKSession();
			s3vn.acquireLock();
			currentLocal = s3vn.getCurrent();
			currentZoo = s3vn.fetchCurrent();
			if (currentLocal > currentZoo)
				throw new Exception(String.format("ZooKeeper is out of date!\nZooKeeper version: %d\nLocal version: %s", currentZoo, currentLocal));
			for (rev = currentLocal+1; rev <= currentZoo; rev++){
				System.out.println(String.format("StartCommitHook: for-loop: rev=%d currentLocal=%d currentZoo=%d", rev, currentLocal, currentZoo));
				s3vn.fetchRev(rev);
			}
			s3vn.setCurrent(currentZoo);
			s3vn.saveZKSession();
			ret = 0;
		}catch (Exception e){
			System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
			StackTraceElement[] ste = e.getStackTrace();
			int i;
			for (i = 0; i < ste.length; i++){
				System.out.println(ste[i]);
			}
			failure = true;
			ret = 1;
		}/*finally{
			try{
				if (!failure){
					s3vn.releaseLock();
					s3vn.endZKSession();
				}
			}catch (Exception e){
				System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
				StackTraceElement[] ste = e.getStackTrace();
				int i;
				for (i = 0; i < ste.length; i++){
					System.out.println(ste[i]);
				}
			}
		}*/
		System.exit(ret);
	}
}
